import { Body, Controller, Delete, Get, Param, Post, Put, Query, UsePipes } from '@nestjs/common';
import { isNumber } from 'class-validator';
import dtoValidationPipe from 'src/pipe/Dto.pipe';
import { RedisService } from 'src/redis/redis.service';
import { errorReturn, successReturn } from 'src/utils';
import { AddDto, EditDto, ListDto } from './dto/Common.dto';
import { IotSimService } from './iot-sim.service';

@Controller('iotSim')
export class IotSimController {
    constructor(
        private iotSimService:IotSimService,
        private redisService:RedisService
    ) {}

    @Get('list')
    @UsePipes(dtoValidationPipe({skipMissingProperties : true}))
    iotsimList(@Query() dto:ListDto) {
        return this.iotSimService.iotsimList(dto)
    }

    @Get('list/:cardNo')
    async querySimByCardNo(@Param('cardNo') cardNo:string) {
        let rows = await this.iotSimService.querySimByCardNo(cardNo)

        return rows
    }
    
    @Post('add')
    @UsePipes(dtoValidationPipe())
    async addMerchant(@Body() dto:AddDto) {
        try {
            if((await this.iotSimService.cardNoIsExists(dto.cardNo)) == true) return errorReturn('卡号已经存在')
            const lockKey = dto.cardNo + 'iot::add:lock'
            const lock = await this.redisService.store.set(lockKey,'', {NX : true, EX : 10})
            if(!lock) return errorReturn()
            const id = await this.iotSimService.add(dto)
            this.redisService.del(lockKey)
            return successReturn()
        } catch (error) {
            
        }

        return errorReturn()
    }

    @Put('edit/:id')
    @UsePipes(dtoValidationPipe({skipMissingProperties : true}))
    async editMerchant(@Param('id') id:number, @Body() dto:EditDto) {
        id = Number(id)
        if(!isNumber(id) || id <= 0) return errorReturn()
        try {
            // if(dto.cardNo) {
            //     if((await this.iotSimService.cardNoIsExists(dto.cardNo)) == true) return errorReturn('卡号已经存在')
            // }
            const res = await this.iotSimService.edit(id, dto)
            if(res) {
                return successReturn()
            }
        } catch (error) {
            return errorReturn(error.message)
        }

        return errorReturn()
    }

    @Delete('delete')
    async delete(@Body('ids') ids : number[]) {
        if(!ids || ids.length == 0 || !ids.every(id => !isNaN(id))) return errorReturn()
        try {
            let result = await this.iotSimService.delete(ids)
            if(result) {
                return successReturn('删除成功')
            }else {
                return errorReturn('删除失败')
            }
        } catch (error) {
            return errorReturn(error.message)
        }
    }
}
